import React from 'react';
import {View} from "@gluestack-ui/themed";
import {Table, TableWrapper, Row, Rows, Cell, Col} from 'react-native-table-component';
import {useTheme} from "@/hooks"
import {NativeScrollEvent, NativeSyntheticEvent, StyleSheet} from "react-native";
import TableHead from "./TableHead";
import TableBody from "./TableBody";
import {tableData as tData} from "@/mock/table";
import {TableContext} from "./context";
import {TableProps, ScrollInstance} from "./types";

const styles = StyleSheet.create({
    container: {
        flex: 1,
        borderRadius: 16,
        overflow: "hidden"
    },
});

const KTable = (props: TableProps) => {
    const {colors} = useTheme();
    const {
        columns,
        color = colors.textLight950,
        headerBgColor = "#fafafa",
        borderBottomWidth = 0.5,
        borderColor = "#e8e8e8",
        cellDefaultWidth = 80,
        fontSize = 14,
        headerFontSize = 14,
        headerHeight = 40,
        children
    } = props;
    const [tableData, setTableData] = React.useState<any[]>(tData);
    const fixedColumns = columns.filter(column => column.fixed);
    const normalColumns = columns.filter(column => !column.fixed);
    const tableHeadRef = React.useRef<ScrollInstance>(null);
    const tablefootRef = React.useRef<ScrollInstance>(null);

    function handleScroll(e: NativeSyntheticEvent<NativeScrollEvent>) {
        const {y, x} = e.nativeEvent.contentOffset;
        const options = {
            x,
            animated: false
        }
        tableHeadRef.current!.scrollTo(options);
        tablefootRef.current!.scrollTo(options);
    }

    return (
        <View
            style={[styles.container]}
            bg={colors.white}
            mt={15}
        >
            <TableContext.Provider value={{
                data: tableData,
                normalColumns,
                fixedColumns,
                color,
                headerBgColor,
                borderBottomWidth,
                borderColor,
                cellDefaultWidth,
                fontSize,
                headerFontSize,
                headerHeight,
            }}>
                <TableHead ref={tableHeadRef}>
                    {children?.header}
                </TableHead>
                <TableBody onScroll={handleScroll}>
                    {children?.body}
                </TableBody>
                <TableHead ref={tablefootRef}>
                    {children?.header}
                </TableHead>
            </TableContext.Provider>
        </View>
    );
};

export default KTable;